/**
* ...
* @author Ludo
* @version 1.1
*/

import clases.MadParser.IndividualStats.MadJugador;
import clases.MadParser.MadParser;
import clases.utils.MadCeldaMultilinea;
import mx.controls.gridclasses.DataGridRow;
import mx.utils.Delegate;
import flash.external.ExternalInterface;
import mx.controls.DataGrid;
import mx.controls.gridclasses.DataGridColumn;
import mx.styles.CSSStyleDeclaration;


class clases.MadPlayByPlay extends MovieClip {

	// Modo local
	public static var local:Boolean = false;

	// Ruta
	public static var pathLocal:String = "xml/PlayByPlay";

	// Fichero XML
	private var xmlFile:XML;
	
	// Parseador
	private var madParser:MadParser;

	// Grid
	public var grid:DataGrid;
	
	// Textos
	public var minute:String;
	public var team1:String;
	public var team2:String;
	public var score:String;
	
	// Elementos
	public var mcAnimacion:MovieClip
	public var mcFondoGris:MovieClip
	public var mcFondo2:MovieClip
	public var mcBotones:MovieClip;
	public var mcDisable:MovieClip;
	// Ultimo cuarto mostrado, el movieclip y el numero
	
	public var mcLastQuarter:MovieClip;
	public var actualQuarter:Number;
	
	public var mcEventos:MovieClip;
	
	public static var numberOfEventsToShowOnLoad:Number = 7;
	
	
	

	public function MadPlayByPlay() 
	{
		mcDisable._alpha = 0;
		mcDisable._visible = false;
		mcDisable.useHandCursor = false;
		mcDisable.onPress = function() { };
		mcEventos.gotoAndStop(1);
		mcEventos._visible = false;
		this._visible = false;
		ExternalInterface.addCallback("pasaXMLPlayByPlayAFlash", null, Delegate.create(this, onLoadExternalXML));
		ExternalInterface.addCallback("preparaCarga", null, Delegate.create(this,preparaCarga));
		ExternalInterface.addCallback("errorProducido", null, Delegate.create(this,errorCargaExterna));
		ExternalInterface.addCallback("reinicia", null, Delegate.create(this,reinicia));
		
		preparaLiterales();
		actualQuarter = 0;
		madParser = new MadParser();
		if(local)
		{
			getLocalXML(0);
		}
		else
		{
			preparaCarga();
			ExternalInterface.call("cargaPlayByPlay",0,100);
		}
		Stage.scaleMode = "noScale";
		Stage.align = "TL";
		Stage.addListener(this);
	}
	
	private function onResize()
	{
		grid.selectable = true;

		grid.setSize(Stage.width - grid._x, grid.height,true);
		mcAnimacion._x = Stage.width/2 - mcAnimacion._width / 2;
		mcBotones._x = Stage.width/2 - mcBotones._width / 2;
		mcFondoGris._width = Stage.width;
		mcFondo2._width = Stage.width;
		
		grid.vScroller.move(grid.vScroller.x, grid.vScroller.y+25);
		grid.vScroller.setSize(grid.vScroller.width, grid.vScroller.height - 25);
		
		for (var i = 0; i < grid.rows.length; ++i)
		{
			grid.selectRow(i, false,false);
		}				
		
		grid.selectable = false;

	}
	
	private function preparaLiterales()
	{
		minute = _level0.Minute;
		score = _level0.Score;
		if(minute == undefined) minute = "MIN";
		if(score == undefined) score = "SCORE";
		
	}
	
	private function getLocalXML(quarter:Number)
	{
		preparaCarga();

		xmlFile = new XML();
		xmlFile.ignoreWhite = true;
		xmlFile.onLoad = Delegate.create(this,onLoadXML);
/*		xmlFile.onLoad = function(ok)
		{
			trace(this);
		}*/
		xmlFile.load(pathLocal + quarter + ".xml");
	}
	
	private function onLoadXML(ok:Boolean)
	{
		if(ok)
		{
			changePlayByPlay(xmlFile.toString());
		}
		else
		{
			trace("** ERROR ** Carga de " + pathLocal);
		}
	}
	
	private function onLoadExternalXML(data:String)
	{
		trace("Llego al cambio de individual stats con " + this);
		changePlayByPlay(data);
	}	
	
	private function prepareGrids()
	{
		var obj = new Object();
		

		grid.addEventListener("load", Delegate.create(this,onResizeGrid));
		grid.addEventListener("headerRelease", Delegate.create(this,onReleaseHeaderGrid));
		grid.addEventListener("itemRollOver", Delegate.create(this, onRollOverGrid));
		grid.addEventListener("itemRollOver", Delegate.create(this, onRollOverGrid));
		

		
		grid.setStyle("borderStyle", "none");
		grid.setStyle("borderCapColor", 0xFFFFFF);
		grid.setStyle("shadowCapColor", 0xFFFFFF);
		grid.setStyle("shadowColor", 0xFFFFFF);
		grid.setStyle("borderColor", 0xFFFFFF);
		grid.setStyle("hGridLines", true);
		grid.setStyle("color", 0xFFFFFF);
		grid.setStyle("hGridLineColor", 0xE66007);
		grid.setStyle("backgroundColor", 0x000000);
		grid.setStyle("rollOverColor", 0x4B4B4B);
		grid.setStyle("textRollOverColor", 0xFFFFFF);
		grid.setStyle("selectedColor", 0x4B4B4B);
		grid.setStyle("themeColor", 0x4B4B4B);
		
		var headerStyles = new CSSStyleDeclaration();
		headerStyles.setStyle("fontFamily", "Black");
		headerStyles.setStyle("fontSize", 8);
		headerStyles.setStyle("embedFonts", true);
		headerStyles.setStyle("fontWeight ", "bold");
		headerStyles.setStyle("color", 0xFFFFFF);
		grid.setStyle("headerStyle", headerStyles);
		

		grid.setStyle("vGridLines", false);		
		
		mx.controls.DataGrid.prototype.drawHeaderBG = function(Void) {

			with(this)
			{
				
				var mc : MovieClip = header_mc;
				
				
				mc.clear();

			}
		};

		team1 = madParser.team1;
		team2 = madParser.team2;
		if(team1 == undefined) team1 = "VIRTUS VIDIVICI BOLOGNA";
		if(team2 == undefined) team2 = "VIRTUS VIDIVICI BOLOGNA";
		
		grid.resizableColumns = false;
		grid.hScrollPolicy = "none";
		grid.vScrollPolicy = "auto";
		grid.showHeaders = true;
		grid.headerHeight = 25;
		grid.rowHeight = 50; 
		grid.useHandCursor = false;
		grid.setStyle("valign", "center");
		
		var columna:DataGridColumn = new DataGridColumn;
		columna = new DataGridColumn("min");
		columna.headerText = minute;
		columna.editable = false;
		columna.sortable = true;
		columna.sortOnHeaderRelease = true;
		columna.width = 38.1;
		columna.fontSize = 9;
		columna.cellRenderer = "MadCeldaMultilinea";
		columna.headerRenderer = "MadCeldaMultilinea_Header";
		columna.textAlign = "center";

		grid.addColumn(columna);
		

		var columna:DataGridColumn = new DataGridColumn;
		columna = new DataGridColumn("team1");
		columna.headerText = team1;
		columna.editable = false;
		columna.sortOnHeaderRelease = true;
		columna.fontSize = 9;	
		columna.width = 87.7;
		columna.textAlign = "center";

		columna.cellRenderer = "MadCeldaMultilinea";
		columna.headerRenderer = "MadCeldaMultilinea_Header";

		grid.addColumn(columna);
		
		var columna:DataGridColumn = new DataGridColumn;
		columna = new DataGridColumn("score");
		columna.headerText = score;
		columna.editable = false;
		columna.sortable = true;
		columna.sortOnHeaderRelease = true;
		columna.width = 41.2;
		columna.fontSize = 9;
		columna.textAlign = "center";
		columna.cellRenderer = "MadCeldaMultilinea";
		columna.headerRenderer = "MadCeldaMultilinea_Header";
		
		
		grid.addColumn(columna);
		
		var columna:DataGridColumn = new DataGridColumn;
		columna = new DataGridColumn("team2");
		columna.headerText = team2;
		columna.editable = false;
		columna.sortable = true;
		columna.sortOnHeaderRelease = false;
		columna.fontSize = 9;	
		columna.width = 87;
		columna.cellRenderer = "MadCeldaMultilinea";
		columna.headerRenderer = "MadCeldaMultilinea_Header";
		columna.textAlign = "center";
		
		grid.addColumn(columna);
		


		
	}
	
	private function changePlayByPlay(data:String):Boolean
	{
		grid._visible = false;
		if (!madParser.parsePlayByPlay(data))
		{
			errorParseado();
			return false;
		}
		
		if(actualQuarter == 0)
		{
			actualQuarter =  madParser.actualPartial;
		}
		// Preparo ya la precarga
		if(!local)
		{
			ExternalInterface.call("cargaPlayByPlay",actualQuarter,madParser.expires*1000);
		}
		else
		{
			var intervalo = setInterval(this,"changePlayByPlay",60000,xmlFile.toString());
		}
		
		// Preparo el grid;
		var hasToPrepareGrids = false;
		if(grid.columnCount < 2)
		{
			hasToPrepareGrids = true;
			prepareGrids();
		}
		
		
		var numQuarter = madParser.actualPartial;
		
		if(numQuarter > 5) numQuarter = 5;
		
		for(var i=numQuarter+1;i<5;i++)
		{
			var mc = eval(mcBotones["mcQ"+i]);
			mc.enabled = false;
		}
		
		trace("El cuarto actual es " + actualQuarter);
		mcLastQuarter.gotoAndStop(1);
		mcLastQuarter.enabled = true;
		mcBotones["mcQ"+ actualQuarter].gotoAndStop(2);
		mcBotones["mcQ"+ actualQuarter].enabled = false;
		mcLastQuarter = mcBotones["mcQ"+ actualQuarter];
		
		
		if(numQuarter > 0)
		for(var i=1;i<=numQuarter;i++)
		{
			var mc = eval(mcBotones["mcQ"+i]);
			mc.quarter = i;
			var buttonListener:Object = new Object();
			
			mc.padre = this;
			mc.onRelease = function()
			{
				this.padre.loadQuarter(this.quarter);
			}
		}
		
		trace(actualQuarter);
		grid.dataProvider = madParser.getActionsOfQuarter(actualQuarter);


		//grid.dataProvider = [{min:45}];

		
		
		grid.doLater(this, "onResizeGrid");
		this._visible = true;
		return true;

	}
	
	private function loadQuarter(quarter:Number)
	{
		mcLastQuarter.gotoAndStop(1);
		mcLastQuarter.enabled = true;
		mcBotones["mcQ"+ quarter].Quarter.textColor = 0xFFFFFF; 
		mcBotones["mcQ"+ quarter].enabled = false;
		mcBotones["mcQ"+ quarter].gotoAndStop(2);
		actualQuarter = quarter;
		
		
		// Preparo ya la precarga
		if(!local)
		{
			ExternalInterface.call("cargaPlayByPlay",quarter,100);
		}
		else
		{
			getLocalXML(quarter);
		}
	}
	
	private function finalizePrepareGrids()
	{
		
	}


	public function onResizeGrid()
	{
		this.onEnterFrame = function()
		{
			grid._visible = false;
			for (var i = 0; i < grid.rows.length; ++i)
			{
				grid.rows[i].backGround._alpha = 0;
				grid.border_mc.backgroundColorName = "nosense";
				grid.border_mc.drawBorder();
				grid.selectRow(i, false,false);
			}			
			onResize();
			this.onEnterFrame = function()
			{
				quitaCarga();
				grid.clearSelected();			
				if (actualQuarter ==  madParser.actualPartial) showLastEvents();
				
				grid._visible = true;

				delete this.onEnterFrame;
			}
			
		}
	}
	
	public function changeQuarter(quarter:Number)
	{
		grid._visible = false;
		grid.dataProvider = madParser.getActionsOfQuarter(quarter);
		grid.doLater(this, "onResizeGrid");
		
	}
	
	
	public function onReleaseHeaderGrid(evt)
	{
		if(!grid.columns[evt.columnIndex].sortOnHeaderRelease)
		{
			if(evt.target.sortDirection == "ASC"){
				evt.target.dataProvider = evt.target.dataProvider.sortOn(grid.columnNames[evt.columnIndex], Array.NUMERIC)
			} else {
				evt.target.dataProvider = evt.target.dataProvider.sortOn(grid.columnNames[evt.columnIndex], Array.NUMERIC).reverse()
			}
		}
		grid.doLater(this, "onResizeGrid");
	}
	
	public function onRollOverGrid(evt)
	{
		grid.selectedItem
		trace(grid.selectedIndex);
		trace(grid.selectedItem);
		mcEventos._visible = true;
		mcEventos._alpha = 0;
		
		var code:String = new String();
		

			if (grid.selectable)
			{
				if (grid.selectedItem == undefined)
				{
					code = grid.getItemAt(0)["code"];
				}
				else
				{				
					code = grid.selectedItem["code"];
				}
			}
			else
			{
				code = grid.getItemAt(evt.index).code;
			}

		
		trace("Codigo: " + code);
		mcEventos.gotoAndPlay(code);
		mcEventos.onEnterFrame = function() { 
			this._alpha += 10;
			if (this._alpha >= 100)
			{
				this.onEnterFrame = function()
				{
					if (this.fotogramaOrigen == this._currentframe)
					{
						this.onEnterFrame = function()
						{
							this._alpha -= 10;
							if (this._alpha <= 0)
							{
								this._visible = false;
								this.gotoAndStop(1);
								delete this.onEnterFrame;
								if (this._parent.grid.selectable)
								{
									trace(this._parent.grid);
									trace(this._parent.grid.selectedIndex);
									if (this._parent.grid.selectedIndex == undefined)
									{
										this._parent.mcDisable._visible = false;
										this._parent.grid.selectable = false;
										this._parent.grid.selectedIndex = undefined;
									}
									else if (this._parent.grid.selectedIndex != 0)
									{
										trace("Sigue");
										var pos:Number = Math.floor((this._parent.grid.selectedIndex-1) / 4) * 4;
										trace(pos);
										this._parent.grid.vPosition = pos;

										this._parent.grid.selectedIndex  -= 1;
										this._parent.grid.setPropertiesAt(this._parent.grid.selectedIndex, {backgroundColor:0x000000});
										this._parent.onRollOverGrid();
									}
									else
									{
										trace("Libera");
										
										this._parent.mcDisable._visible = false;
										this._parent.grid.selectable = false;
										this._parent.grid.selectedIndex = undefined;
									}
								}
							}
						}
					}
					this.fotogramaOrigen = this._currentframe;
				}				
			}
		}
		//mcEventos.gotoAndPlay(grid.getItemAt(evt.index).code);
	}
	
	private function preparaCarga()
	{
		_level0.mcLoading._visible = true;
		_level0.mcLoading.gotoAnPlay(1);
	}

	private function quitaCarga()
	{
		_level0.mcLoading._visible = false;
		_level0.mcLoading.gotoAnStop(1);
	}	

	private function errorCargaExterna()
	{
		ExternalInterface.call("cargaPlayByPlay",actualQuarter,1000);		
	}

	private function errorParseado()
	{
		ExternalInterface.call("cargaPlayByPlay",actualQuarter,1000);		
	}	
	
	private function showLastEvents()
	{
		//_level0.mcLoading._alpha = 0;
		//_level0.mcLoading._visible = true;
		
		var numberOfActionsToShow:Number = new Number();
		if (madParser.getActionsOfPreviousQuarter(actualQuarter) != undefined)
		{
			trace("Entra por antiguo");
			var total = madParser.getActionsOfQuarter(actualQuarter).length - madParser.getActionsOfPreviousQuarter(actualQuarter);
			if (total > numberOfEventsToShowOnLoad)
			{
				numberOfActionsToShow  = numberOfEventsToShowOnLoad;
			}
			else
			{
				numberOfActionsToShow = total;
			}
		}
		else
		{
			
			trace("TOTAL:" + madParser.getActionsOfQuarter(actualQuarter).length);
			var total = madParser.getActionsOfQuarter(actualQuarter).length;
			if (total > numberOfEventsToShowOnLoad)
			{
				numberOfActionsToShow  = numberOfEventsToShowOnLoad;
			}
			else
			{
				numberOfActionsToShow = total;
			}
		}
		
		
		trace("Numero acciones:" + numberOfActionsToShow);
		if (numberOfActionsToShow > 0)
		{
			grid.vPosition = 0;
			
			
			for (var i = 0; i <= numberOfActionsToShow - 1; i++)
			{
				trace("Cambio " + i);
				grid.rows[i].backGround._alpha = 100;
				grid.setPropertiesAt(i, {backgroundColor:0xCCCCCC});
				
//				var color:Color = new Color(grid.rows[i].backGround);
//				color.setRGB(0xFF0000);
				
				
			}
			
			mcDisable._visible = true;
			grid.selectable = true;
			
			var pos:Number = Math.floor(numberOfActionsToShow / 4)*4;
			
			
			
			grid.vPosition = pos;
			grid.setPropertiesAt(numberOfActionsToShow, {backgroundColor:0x000000});
			grid.selectedIndex = numberOfActionsToShow;
			onRollOverGrid();
		}

	}

	private function reinicia()
	{
		_level0.gotoAndPlay(1);
		delete this;
	}
}